import Koa from 'koa'
import views from 'koa-views'
import convert from 'koa-convert'
import json from 'koa-json'
import onerror from 'koa-onerror';
import bodyparser from 'koa-bodyparser'
import logger from 'koa-logger'
// import mount from 'koa-mount'
import koaStatic from 'koa-static'

import config from './config'
import routes from './routes'
import { join } from 'path'
const app = new Koa()
const debug = require('debug')('app');
onerror(app)

app.keys = ['com.outbook.oss']

// middlewares
app.use(bodyparser())
app.use(convert(json()))
app.use(convert(logger()))
app.use(koaStatic(join(__dirname, '/public')))
app.use(views(join(__dirname, '/views'), {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  ctx.set('X-Response-Time', `${ms}ms`);
  debug(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
app.use(routes.routes(), routes.allowedMethods())
// response

app.on('error', err => {
  debug('app error', err)
})

export default app
